<script lang="ts" setup name="User">
// import { NSwitch } from 'naive-ui';

import type { FormItemRule } from 'naive-ui'
import lang from './lang'

import { useMixins } from '@/hooks/useMixins'

import {
  addUser,
  getUser,
  pageUser,
  resetUserPwd,
  updateUser,
} from '@/api/system/user'
import { getAllRole } from '@/api/system/role'

// import { getOrgTreeSelect } from '@/api/common/organization';

import { deptOrgList } from '@/api/system/dept'

// import { encrypt } from '@/utils/jsencrypt';

// import { defaultPassWord } from './defaultPwd';

import {
  checkEmailFn,
  checkPhoneCodeFn,
} from '@/utils/formCheck'

// import LeftTree from './leftTree.vue';

const {
  loadLangFn,
  getPageLangValueFn,
  // language,
  dialogWarningFn,
  message,
  t,
} = useMixins()

loadLangFn(lang)

const dfPageListRef: any = ref(null)
const leftTreeRef: any = ref(null)

// const changeUserStatusFn = async (data = {}) => {
//   try {
//     const res = await changeUserStatus({ ...data });

//     const { code = 0, message: msg = '' } = res;

//     if (code === 0) {
//       reloadTableFn();
//     }

//     message.success(msg);
//   } catch (e) {
//     console.log(e);
//   }
// };

// const orgCode = ref('');
// const indeterminateKeys: any = ref([]);
const checkValue: any = ref([])
// const defaultValue: any = ref([]);
// const leftTreeSelect = (e) => {
//   orgCode.value = e;
//   dfPageListRef.value && dfPageListRef.value.reloadTableFn();
// };
// const treeSelect = (e: any, v, model) => {
//   console.log(e, v, 5555555);
//   // indeterminateKeys.value = [...e];
//   // defaultValue.value = [...e];
//   checkValue.value = [...e];

//   model['ralUserOrgs'] = v;

//   model['ucDeptList'] = [];

//   treeData2.value = [];

//   checkValue2.value = [];

//   if (e && e.length) {
//     model['orgCode'] = e[0];

//     deptOrgList({ orgList: e }).then((res) => {
//       treeData2.value = res.row;
//     });
//   } else {
//     model['orgCode'] = null;
//   }

//   // console.log(e, v, dfPageListRef.value.getModalFormValFn());
//   // dfPageListRef.value.setFieldsValueFn({
//   //   ...dfPageListRef.value.getModalFormValFn(),
//   //   ralUserOrgs: v,
//   // });
//   // console.log(33334444, dfPageListRef.value.getModalFormValFn());
// };
// const treeSelect2 = (e: any, v, model) => {
//   checkValue2.value = [...e];

//   model['ucDeptList'] = v;
// };
// const treeData = ref<any>([]);
// provide('treeData', treeData);
// const getListDept = async (): Promise<void> => {
//   const { row } = await getOrgTreeSelect();
//   treeData.value = row || [];
// };
// getListDept();

const treeData2: any = ref([])

const checkValue2: any = ref([])

function reloadTableFn() {
  if (dfPageListRef.value)
    dfPageListRef.value.reloadTableFn()
}
function setDialogDataFn(e) {
  checkValue.value = []

  checkValue.value = e.ralUserOrgs?.map(a => a.orgCode) || []

  checkValue2.value = e.ucDeptList?.map(a => a.deptCode) || []

  if (checkValue.value.length) {
    deptOrgList({ orgList: toRaw(checkValue.value) }).then((res) => {
      treeData2.value = res.row
    })
  }

  return e
}
function handleResetPwdFn(recordRow: any) {
  const { id = '' } = recordRow

  dialogWarningFn(
    {
      content: getPageLangValueFn('tipsMsg.resetPwdMsg'),
    },
    null,
    null,
    {
      onPositiveClick: async () => {
        try {
          const { message: msg = '' }: any = await resetUserPwd({
            id,
          })

          reloadTableFn()

          message.success(msg)
        }
        catch (_e) { }
      },
    },
  )
}

const rolesList = ref([])

async function getAllRoleListFn() {
  try {
    const res = await getAllRole()

    const { data = [] } = res

    if (data && data.length) {
      const list: any = []

      for (const item of data) {
        const { name = '', id = '' } = item

        list.push({ label: name, value: id })
      }

      rolesList.value = list
    }
  }
  catch (_e) { }
}

async function beforeOpenDialogFn(data) {
  if (JSON.stringify(data) === '{}')
    checkValue.value = []

  try {
    await getAllRoleListFn()

    return true
  }
  catch (_e) { }

  return false
}

function setDialogSubmitDataFn(data = {}, _type) {
  let obj = {}

  if (data)
    obj = data

  // if (type === 'add' && obj['password']) {
  //   obj['password'] = encrypt(obj['password']);
  // }

  // if (obj['ucDeptList'] && obj['ucDeptList'].length) {
  //   obj['ucDeptList'] = obj['ucDeptList'].map((e) => ({
  //     deptCode: e.deptCode,
  //     deptName: e.deptName,
  //     userName: obj['userName'],
  //     orgCode: e.orgCode,
  //   }));
  // }

  return obj
}
function beforeResetFn() {
  leftTreeRef.value && leftTreeRef.value?.setValue('')
}
const pageOptions = {
  searchForm: {
    formSchemas: [
      {
        component: 'NInput',
        label: 'userName',
        common: true,
      },
      {
        component: 'NInput',
        label: 'nickName',
        common: true,
      },
      {
        component: 'NSelect',
        label: 'status',
        common: true,
        options: [
          {
            label: getPageLangValueFn('table.able'),
            value: 1,
          },
          {
            label: getPageLangValueFn('table.disable'),
            value: 0,
          },
        ],
      },
    ],
    beforeResetFn,
  },
  table: {
    columns: [
      {
        width: 120,
        label: 'userName',
        common: true,
      },
      {
        width: 120,
        label: 'nickName',
        common: true,
      },
      {
        width: 120,
        label: 'phoneNo',
        key: 'phone',
        common: true,
      },
      {
        width: 150,
        label: 'userEmail',
        key: 'email',
        common: true,
      },
      // {
      //   width: 120,
      //   title: '用户工号',
      //   key: 'userNo',
      // },
      // {
      //   width: 100,
      //   label: 'userSex',
      //   common: true,
      //   key: 'sex',
      //   render(row) {
      //     return h('span', {
      //       innerText:
      //         row.sex === 0
      //           ? getPageLangValueFn('table.male')
      //           : row.sex === 1
      //           ? getPageLangValueFn('table.female')
      //           : '-',
      //     });
      //   },
      // },
      // {
      //   width: 100,
      //   label: 'userNo',
      //   key: 'userNo',
      // },
      // {
      //   width: 100,
      //   label: 'delFlag',
      //   render(row: any) {
      //     const { userName = '', id = '' } = row;

      //     const cancelFn = () => {
      //       row.delFlagLoading = false;
      //     };

      //     return h(
      //       NSwitch,
      //       reactive({
      //         value: !(row.delFlag === 0),
      //         loading: !!row.delFlagLoading,
      //         // loading: loading.value,
      //         'on-update:value': async (value) => {
      //           row.delFlagLoading = true;

      //           const text = getPageLangValueFn(`table.${value ? '' : 'un'}lock`);

      //           dialogWarningFn(
      //             {
      //               content: `${t('common.tipMsg.primary')}${
      //                 language.value === 'zh' ? text : ' ' + text + ' '
      //               }"${userName}"?`,
      //             },
      //             async () => {
      //               try {
      //                 await changeUserStatusFn({
      //                   id,
      //                   delFlag: value ? 1 : 0,
      //                 });
      //               } catch (e) {
      //                 console.log(e);
      //               }
      //               row.delFlagLoading = false;
      //             },
      //             cancelFn,
      //             {
      //               onNegativeClick: cancelFn,
      //               onClose: cancelFn,
      //               onMaskClick: cancelFn,
      //             }
      //           );
      //         },
      //       } as any)
      //     );
      //   },
      // },
      // {
      //   width: 100,
      //   label: 'status',
      //   common: true,
      //   render(row) {
      //     const { userName = '', id = '' } = row;

      //     const cancelFn = () => {
      //       row.statusLoading = false;
      //     };

      //     return h(NSwitch, {
      //       value: row.status === 1,
      //       loading: !!row.statusLoading,
      //       'on-update:value': async (value) => {
      //         row.statusLoading = true;

      //         const text = getPageLangValueFn(`table.${value ? 'enable' : 'disable'}`);

      //         dialogWarningFn(
      //           {
      //             content: `${t('common.tipMsg.primary')}${
      //               language.value === 'zh' ? text : ' ' + text + ' '
      //             }"${userName}"?`,
      //           },
      //           async () => {
      //             try {
      //               await changeUserStatusFn({
      //                 id,
      //                 status: value ? 0 : 1,
      //               });
      //             } catch (e) {
      //               console.log(e);
      //             }

      //             row.statusLoading = false;
      //           },
      //           cancelFn,
      //           {
      //             onNegativeClick: cancelFn,
      //             onClose: cancelFn,
      //             onMaskClick: cancelFn,
      //           }
      //         );
      //       },
      //     });
      //   },
      // },
    ],
    action: {
      widthEn: 170,
      columns: [
        {
          label: 'edit',
        },
        {
          label: 'resetPwd',
          click: (row) => {
            handleResetPwdFn(row)
          },
        },
      ],
    },
    operaColumn: [
      {
        label: 'add',
      },
    ],
    requestFn: pageUser,
    // beforeSlotName: 'tree',
    // setRequestDataFn: (e) => {
    //   console.log(e, 3333333333);
    //   const { entity } = e;
    //   e.entity = {
    //     ...entity,
    //     orgCode: orgCode.value,
    //   };
    //   return {
    //     ...e,
    //   };
    // },
  },
  modalFormDialog: {
    formSchemas: [
      {
        label: 'userName',
        common: true,
        editDialogDisabled: true,
        required: true,
        checkZhCode: true,
        maxlength: 30,
      },
      {
        label: 'nickName',
        common: true,
        required: true,
        maxlength: 30,
        componentProps: {
          'input-props': { autocomplete: `new-password` },
        },
      },
      // {
      //   label: 'password',
      //   common: true,
      //   defaultValue: `${defaultPassWord}`,
      //   editDialogHidden: true,
      //   minlength: 6,
      //   maxlength: 20,
      //   type: 'password',
      //   componentProps: {
      //     'show-password-on': 'click',
      //     'input-props': { autocomplete: `new-password` },
      //   },
      //   rules: [
      //     {
      //       required: true,
      //       validator(_rule: FormItemRule, value: string) {
      //         return checkPassWordFn(value, true);
      //       },
      //       trigger: ['blur'],
      //     },
      //   ],
      // },
      // {
      //   prop: 'sex',
      //   component: 'NRadioGroup',
      //   label: 'userSex',
      //   common: true,
      //   defaultValue: 0,
      //   componentProps: {
      //     options: [
      //       {
      //         label: getPageLangValueFn('table.male'),
      //         value: 0,
      //       },
      //       {
      //         label: getPageLangValueFn('table.female'),
      //         value: 1,
      //       },
      //     ],
      //   },
      // },
      // {
      //   prop: 'ralUserOrgs',
      //   label: 'ralUserOrgs',
      //   slot: 'ralUserOrgs',
      //   rules: [
      //     {
      //       type: 'array',
      //       required: true,
      //       message: t('common.formTipMsg.select'),
      //       trigger: ['change'],
      //     },
      //   ],
      //   giProps: { span: 2 },
      // },
      // {
      //   label: 'defaultOrg',
      //   slot: 'defaultOrg',
      //   prop: 'orgCode',
      //   required: true,
      //   giProps: { span: 2 },
      //   hidden: computed(() => !checkValue.value.length),
      // },
      {
        prop: 'roles',
        component: 'NSelect',
        label: 'role',
        common: true,
        defaultValue: [],
        options: rolesList,
        componentProps: {
          multiple: true,
          maxTagCount: 3,
        },
        rules: [
          {
            type: 'array',
            required: true,
            message: t('common.formTipMsg.select'),
            trigger: ['change'],
          },
        ],
      },
      // {
      //   prop: 'userNo',
      //   label: 'userNo',
      // },
      {
        prop: 'phone',
        label: 'phoneNo',
        common: true,
        maxlength: 30,
        rules: [
          {
            required: true,
            validator(_rule: FormItemRule, value: string) {
              return checkPhoneCodeFn(value, true)
            },
            trigger: ['blur'],
          },
        ],
      },
      {
        label: 'email',
        common: true,
        maxlength: 50,
        rules: [
          {
            required: false,
            validator(_rule: FormItemRule, value: string) {
              return checkEmailFn(value, false)
            },
            trigger: ['blur'],
          },
        ],
      },
      // {
      //   prop: 'ucDeptList',
      //   label: 'ucDeptList',
      //   slot: 'ucDeptList',
      //   giProps: { span: 2 },
      // },
      {
        component: 'NSwitch',
        label: 'status',
        common: true,
        defaultValue: 1,
        componentProps: {
          checkedValue: 1,
          uncheckedValue: 0,
        },
      },
      {
        label: 'remark',
        common: true,
        type: 'textarea',
        giProps: { span: 2 },
      },
    ],
    cols: 2,
    getDataFn: getUser,
    addDataFn: addUser,
    updateDataFn: updateUser,
    beforeOpenDialogFn,
    setDialogSubmitDataFn,
    setDialogDataFn,
  },
}
</script>

<template>
  <div class="user">
    <!-- <div class="left-main">
      <LeftTree />
    </div> -->
    <DFPageList ref="dfPageListRef" :page-options="pageOptions">
      <!-- <template #tree>
        <div class="left-main">
          <LeftTree ref="leftTreeRef" class="left-class" @reloadTable="leftTreeSelect" />
        </div>
      </template> -->
      <!-- <template #ralUserOrgs="{ model }">
        <n-tree-select
          clearable
          block-line
          filterable
          :options="treeData"
          label-field="label"
          key-field="orgCode"
          :multiple="true"
          checkable
          :value="checkValue"
          :cascade="false"
          :check-strategy="'all'"
          :default-expand-all="true"
          :max-tag-count="3"
          @update:value="
            (e, v) => {
              treeSelect(e, v, model);
            }
          "
        />
      </template> -->
      <!-- <template #defaultOrg="{ model }">
        <n-radio-group v-model:value="model.orgCode" name="radiogroup">
          <n-space>
            <n-radio v-for="song in model.ralUserOrgs" :key="song.orgCode" :value="song.orgCode">
              {{ song.label }}
            </n-radio>
          </n-space>
        </n-radio-group>
      </template> -->
      <!-- <template #ucDeptList="{ model }">
        <n-tree-select
          clearable
          block-line
          filterable
          :options="treeData2"
          label-field="deptName"
          key-field="deptCode"
          children-field="deptChildList"
          :multiple="true"
          checkable
          :value="checkValue2"
          :cascade="false"
          :check-strategy="'all'"
          :default-expand-all="true"
          :max-tag-count="3"
          :disabled="!model.ralUserOrgs"
          @update:value="
            (e, v) => {
              treeSelect2(e, v, model);
            }
          "
        />
      </template> -->
    </DFPageList>
  </div>
</template>

<style lang="less" scoped>
:deep(.df-page-list-table) {
  width: calc(100% - 250px) !important;
}

.user {
  .left-main {
    width: 240px;
    height: calc(100vh - 290px);
    background-color: #fff;
    margin-right: 10px;
  }
}
</style>
